package com.abredatos.t37.core

import java.text.SimpleDateFormat;

import com.abredatos.t37.domain.Measure;
import com.abredatos.t37.domain.Pollutant 

class PollutantDataService {

    static transactional = true
	
	def formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

	def loadPollutants() {
		return Pollutant.list()
	}
	
    def loadLastData(String pollutant) {
		return Measure.findAllByPollutant(pollutant, [max:1000])
    }
	
	def loadDataInDate(String dateString) {
		try {
			Date date = formatter.parse(dateString)
			return Measure.findAllByDateTime(date, [max: 60]);
		} catch (ParseException) {
			return []
		}
	}
	
	def loadLastData() {
//		def results = Measure.executeQuery("select max(m.dateTime) from Measure m")
//		java.sql.Timestamp date = results.get(0)
//		long milliseconds = date.getTime()
		long milliseconds = 1293836400000
		return Measure.findAllByDateTime(new Date(milliseconds));
	}
	
	def loadLastDate() {
		def results = Measure.executeQuery("select max(m.dateTime) from Measure m")
		java.sql.Timestamp date = results.get(0)
		long milliseconds = date.getTime()
		return milliseconds;
	}

	def loadLastDataOfStation(stationId, pollutant) {
		def c = Measure.createCriteria()
		def results = c {
			eq("stationId",Long.valueOf(stationId))
			eq("pollutant",pollutant)
			maxResults(24)
			order("dateTime","desc") 
		}
		return results
	}
}
